#! /usr/bin/env python

VERSION='0.1'
APPNAME='gamesys'

srcdir = '.'
blddir = 'build'

import sys, os, re, socket, time
import waf_ddf, waf_graphics, waf_dynamo, waf_physics, waf_render
from waf_dynamo import platform_supports_feature
import waflib.Options
import TestContext
from build_constants import TargetOS

test_context = None

def init(ctx):
    global test_context
    if 'build' in waflib.Options.commands:
        test_context = TestContext.create_test_context()

def options(opt):
    opt.recurse('src')
    opt.load('waf_dynamo')

def configure(conf):
    conf.load('waf_dynamo')
    conf.load('java')
    target_os = conf.env['TARGET_OS']

    waf_ddf.configure(conf)
    waf_graphics.configure(conf)
    waf_physics.configure(conf)
    waf_render.configure(conf)

    if target_os == TargetOS.MACOS:
        conf.env.append_value('LINKFLAGS', ['-framework', 'Cocoa', '-framework', 'OpenGL', '-framework', 'IOKit', '-framework', 'Carbon', '-framework', 'CoreVideo', '-framework', 'QuartzCore'])
    elif target_os == TargetOS.IOS:
        pass
    elif target_os == TargetOS.ANDROID:
        conf.env.append_value('LINKFLAGS', ['-lEGL', '-lGLESv1_CM', '-lGLESv2', '-landroid'])
    elif target_os == TargetOS.WINDOWS:
        conf.env.append_value('LINKFLAGS', ['opengl32.lib', 'user32.lib', 'shell32.lib', 'xinput9_1_0.lib', 'dinput8.lib', 'dxguid.lib'])

    conf.env.append_value('INCLUDES', "default/src")
    conf.env['STLIB_DLIB'] = ['dlib', 'mbedtls', 'zip']
    conf.env['STLIB_DDF'] = 'ddf'
    conf.env['STLIB_RESOURCE'] = 'resource'
    conf.env['STLIB_GAMEOBJECT'] = 'gameobject'
    conf.env['STLIB_EXTENSION'] = 'extension'
    conf.env['STLIB_SCRIPT'] = 'script'
    conf.env['STLIB_RENDER'] = 'render render_font_default'.split()
    conf.env['STLIB_PARTICLE'] = 'particle'
    conf.env['STLIB_RIG'] = 'rig'
    conf.env['STLIB_GUI'] = 'gui'
    conf.env['STLIB_SOUND_NULL'] = 'sound_null'
    conf.env['STLIB_GRAPHICS_GAMESYS_TEST'] = ['graphics_null', 'graphics_transcoder_basisu', 'basis_transcoder']
    conf.env['STLIB_SCRIPT'] = 'script'
    conf.env['STLIB_TEST_SCRIPT'] = 'test_script'

    conf.env.append_unique('DEFINES', 'DLIB_LOG_DOMAIN="GAMESYS"')
    conf.recurse('src')

def build(bld):
    global test_context
    sys.path.insert(0, bld.path.find_dir('src').abspath())
    sys.path.insert(0, os.path.abspath('build/proto/gamesys'))
    sys.path.insert(0, os.path.join(bld.env.PREFIX, 'lib/python/gameobject'))
    sys.path.insert(0, os.path.join(bld.env.PREFIX, 'lib/python/input'))
    sys.path.insert(0, os.path.abspath('src/gamesys/test'))

    bld.recurse('content')
    bld.add_group()
    bld.recurse('src')

    TestContext.initialize_test_context(test_context, bld)

def _get_local_ip(self):
    hostname = socket.gethostname()
    try:
        local_ip = socket.gethostbyname(hostname)
    except socket.gaierror as e:
        print(e)
        print(f"Hostname was '{hostname}', now trying empty ('') string now")
        local_ip = socket.gethostbyname("")
    return local_ip

def server(self):
    import test_script_server

    local_ip = _get_local_ip(self)

    PORT=9001
    configfile = waf_dynamo.create_test_server_config(self, port=PORT, ip=local_ip, config_name="unittest.cfg")

    serv = test_script_server.Server(port=PORT, ip=local_ip)
    serv.start()

    count = 500
    while count > 0:
        count -= 1
        try:
            time.sleep(1)
        except KeyboardInterrupt as e:
            sys.exit(0)


def shutdown(self):

    if not TestContext.is_valid(test_context):
        return

    if getattr(waflib.Options.options, 'skip_tests', False):
        return

    import test_script_server

    local_ip = _get_local_ip(self)

    if test_context.env.PLATFORM in ('win32', 'x86_64-win32', 'x86_64-linux', 'x86_64-macos', 'arm64-macos'):
        local_ip = "localhost"

    PORT=9001
    configfile = waf_dynamo.create_test_server_config(self, port=PORT, ip=local_ip)

    serv = test_script_server.Server(port=PORT, ip=local_ip)
    serv.start()
    try:
        waf_dynamo.run_tests(test_context, valgrind = True, configfile = configfile)
    finally:
        if serv:
            serv.stop()
        os.remove(configfile)
